/**
 * Copyright 2006-2015 handu.com
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iepacj.zk;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZKTest {

	/**
	 * ZooKeeper服务器列表
	 * 客户端第一次连接时, 从这个列表中选择一个进行连接
	 * 如果连接不上, 则选择另外一个进行连接. 只要有一个可以就行
	 * 选择的顺序和书写的顺序没有必然关系
	 * 也就是说, 有可能先跟127.0.0.1:2181尝试连接, 如果连接不上
	 * 就尝试127.0.0.1:3181
	 */
	private static final String connStr = "127.0.0.1:2181,127.0.0.1:2182";
	
	private static final int TIME_OUT = 5000;
	
	CountDownLatch cdl = new CountDownLatch(1);

	public static void main(String[] args) throws Exception {
		new ZKTest().go();
	}
	
	private void go() throws Exception {
		ZkWatcher watcher = new ZkWatcher();
		ZooKeeper zk = new ZooKeeper(connStr, TIME_OUT, watcher);
		System.out.println("zk: " + zk.getState());
		cdl.await();
		System.out.println("zookeeper session established.");
		
		/*
		 * 创建包含数据的znode节点
		 * Ids.OPEN_ACL_UNSAFE 这个参数如果是null, 会报MarshellingError错误
		 */
		//String create = zk.create("/workers", "sss".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		// 返回值是znode路径, 就是第一个参数
		//System.out.println("创建临时节点返回值: " + create);
		
		byte[] data = zk.getData("/workers", watcher, new Stat());
		System.out.println("getData: " + new String(data));



		while (true) {
			
		}
	}

	class ZkWatcher implements Watcher {

		public void process(WatchedEvent event) {
			/*
			 * getPath: /workers
			 * getStat: SyncConnected
			 * getType: NodeDataChanged
			 */
			System.out.println("receive watch event: " + event);
			System.out.println("getPath: " + event.getPath());
			System.out.println("getStat: " + event.getState());
			System.out.println("getType: " + event.getType().name());
			if (KeeperState.SyncConnected == event.getState()) {
				System.out.println("countdown...");
				cdl.countDown();
			}
			EventType eventType = event.getType();
			if (EventType.NodeDataChanged == eventType) {
				System.out.println("node data has changed.");
			}
			if (EventType.NodeDeleted == eventType) {
				System.out.println("node has deleted.");
			}
		}
		
	}

}







